import datetime

from pic_utils import pic_tools, batch_manager, txt_tools
from insects_utils import insects_tools
import sys
import time
import numpy as np
import cv2 as cv
import os
import math
import time
import json
from project_utils import project_tools
from utils.redis_utils import RedisTool
from utils.result_utils import ResultUtil
from model_utils import model_tools
from sklearn.svm import LinearSVC
import redis
import shutil



# flask具有轻量、简捷易上手的特点，适合新手使用
from flask import Flask
# request用于接收数据
from flask import request
# 解决跨域问题
from flask_cors import CORS
from app import app


# 建立与阿里云服务器redis的连接，并获取操作实例
# r=redis.StrictRedis(host='39.102.44.159', port=6379, db=0, password='inetlabredis', decode_responses=True)
r = RedisTool(host='43.137.16.144', port=6379, db=0)
# 准备工作文件夹
project_root_dir = project_tools.project_root_path() + os.sep + 'insects_detection'
project_tools.prepare_working_dirs(project_root_dir)
# # 设定文件读取路径
# gallery_path = "/home/lizhenghao/PycharmProjects/insects_detection_flask_backend/insects_detection/insects_imgs/insects_data/June"
#                # "/home/lizhenghao/insects_data/insects_images/June"
gallery_path = project_root_dir+os.sep+project_tools.insects_img_dirname+os.sep+"tmzx"
# # gallery_path='D:\\1Learning\江苏大学\虫害识别图像数据\第二次病虫害数据图像（03.03）'
model_path = project_root_dir + os.sep + project_tools.models_dirname + os.sep + project_tools.model_name
# single_img_path = project_root_dir + os.sep + project_tools.single_img_processing_dirname
# # 测试代码
# pic_tools.rename_imgs(gallery_path, '1', '.jpg')
processed_gallery_path = project_root_dir + os.sep + project_tools.processed_img_dirname
# # 图像预处理（降低分辨率、抠图、重命名）
store_folder_path = pic_tools.write_all_processed_imgs(gallery_path, processed_gallery_path)
# print(store_folder_path)
# # 查看计数的效果
# count_img=insects_tools.insects_count_visualization(processed_imgs_path+os.sep+"apr"+os.sep+'1-1-1-A.jpg')
# pic_tools.write_single_imgs(single_img_path,count_img)
# insects_tools.get_insects_count_base64(processed_imgs_path + os.sep + '1-9-4-A.jpg', False, False, r, True)
# # 获取温室大棚病虫害计数信息
# start=time.perf_counter()
# if pic_tools.read_imgs_from_dir(processed_imgs_path)==[]:
#     pic_tools.write_all_processed_imgs(gallery_path,processed_imgs_path)
#     print(insects_tools.green_house_insects_info(processed_imgs_path))
# else:
#     print(insects_tools.green_house_insects_info(processed_imgs_path))
# end=time.perf_counter()
# print('Running time: %s Seconds'%(float(end-start)))
#
processed_imgs_path = project_root_dir + os.sep + project_tools.processed_img_dirname+os.sep+"tmzx"
chas_data_path = project_root_dir + os.sep + project_tools.characteristic_dirname
# # 获取所有图片上昆虫的特征矩阵
pic_tools.extract_all_imgs_characteristcs(processed_imgs_path,chas_data_path)
# #
# # # 虫种学习模块
# img_path='F:\python project\Code warehouse\insects_detection_flask_backend2\insects_detection\\5-2-1-B.jpg'
# img=pic_tools.read_imgs(img_path)
# filename = os.path.splitext(img_path)[0].rsplit(os.sep, 1)[1]
# insects_chas,insects_tags=pic_tools.extract_single_insect_img(img)
# pic_tools.save_insects_tags(insects_tags,filename)
# pic_tools.save_random_extracted_insects_chas(insects_chas,filename)
# #
# # 构建虫害识别模型
# base_insects_chas,base_insects_tags=model_tools.merge_insects_chas_and_tags([
#      'D:\python\workspace\insects_detection\insects_tags\\1-1-3-B.txt',
#      'D:\python\workspace\insects_detection\insects_tags\\1-1-4-B.txt',
#      'D:\python\workspace\insects_detection\insects_tags\\1-2-4-A.txt',
#      'D:\python\workspace\insects_detection\insects_tags\\1-8-4-B.txt',
#      'D:\python\workspace\insects_detection\insects_tags\\1-9-2-A.txt',
#      'D:\python\workspace\insects_detection\insects_tags\\1-9-3-A.txt',
#      ])
# model=LinearSVC(max_iter=1000000,C=300)
# model_tools.construct_model(base_insects_chas,base_insects_tags,model,'Model4April')
#
insects_chas_path =project_root_dir+os.sep + project_tools.characteristic_dirname+os.sep+"tmzx"
# # 获取温室大棚病虫害分类计数信息
scaler_path=project_root_dir + os.sep + project_tools.models_dirname + os.sep + 'Model4May_scaler.pkl'
# scaler_path=r'E:\code\NjjProject\NJJ_Algorithm_identification\BingCH\insects_detection_flask_backend2\insects_detection\\trainning_models\\Model4April_scaler.pkl'
detailed_insects_info = insects_tools.classify_green_house_insects(insects_chas_path,model_path,scaler_path)

def detailedInsectsInfo(file_path):
    detailed_insects_info = insects_tools.classify_green_house_insects(file_path, model_path, scaler_path)
    return detailed_insects_info

print(detailed_insects_info)
# print(insects_tools.classify_green_house_insects(insects_chas_path,model_path,scaler_path))
print(insects_chas_path)
# #
# # redis写入相关操作
# info_key='insects:Apr:test'
# r.update(info_key, detailed_insects_info)
# result=r.read(info_key)
# print(result)
#
# # redis正则表达式获取键值集合
# pattern = 'insects:Dec:test'
# matched_keys = r.get_matched_keys(pattern)
# print(matched_keys)
# mresults = r.mread(matched_keys)
# print(mresults)
# print(ResultUtil.sort_result_by_date(mresults, 'last_update_time'))
#
# # 功能测试区
# print(insects_tools.classify_insects_on_single_chas_file('D:\python\workspace\insects_detection\chas_data\\1-1-3-B.txt','D:\python\workspace\insects_detection\\trainning_models\\Model4April.pkl',scaler_path))

# 自动清空文件夹
def delete_folder_contents(folder_path):
    try:
        # 删除文件夹中的文件
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)  # 递归删除子文件夹和文件
        print(f"成功删除 {folder_path} 中的所有内容。")
    except Exception as e:
        print(f"删除 {folder_path} 内容时出错：{str(e)}")

# 指定要删除内容的文件夹路径
folder_to_clear_1 = r"E:\code\NjjProject\NJJ_Algorithm_identification\BingCH\insects_detection_flask_backend2\insects_detection\processed_imgs\tmzx"
folder_to_clear_2 = r"E:\code\NjjProject\NJJ_Algorithm_identification\BingCH\insects_detection_flask_backend2\insects_detection\insects_imgs\tmzx"
folder_to_clear_3 = r"E:\code\NjjProject\NJJ_Algorithm_identification\BingCH\insects_detection_flask_backend2\insects_detection\chas_data\tmzx"

delete_folder_contents(folder_to_clear_1)
delete_folder_contents(folder_to_clear_2)
delete_folder_contents(folder_to_clear_3)

# #  创建flask服务对象
# app = Flask(__name__)
# #  动态解决前端跨域问题
# CORS(app, supports_credentials=True)
# #  开启flask调试模式
# app.debug = True
# #  指定请求路径、方法
# # @app.route('/log', methods=['GET'])
# @app.route('/log')
# def log():
#     # get请求数据获取
#     # log.info("123456")
#     # post请求数据获取
#     # request.form.get("log")
#     # data = request.args.get("log")
#     ret_msg = 'success'
#     return ret_msg
#
# if __name__== "__main__":
#     #  指定端口号和地址
#     app.run(port=1234)